package cn.longwingstech.intelligence.agent.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.longwingstech.intelligence.agent.common.constant.RedisConstant;
import cn.longwingstech.intelligence.agent.model.dto.user.UserLoginRequest;
import cn.longwingstech.intelligence.agent.model.dto.user.UserRegisterRequest;
import cn.longwingstech.intelligence.agent.model.dto.user.UserUpdateRequest;
import cn.longwingstech.intelligence.agent.model.vo.user.UserLoginVO;
import cn.longwingstech.intelligence.agent.model.vo.user.UserVO;
import cn.longwingstech.intelligence.agent.mq.consumer.vo.EmailMqDTO;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.longwingstech.intelligence.agent.model.entity.User;
import cn.longwingstech.intelligence.agent.service.UserService;
import cn.longwingstech.intelligence.agent.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author a1369
* @description 针对表【user(用户信息表)】的数据库操作Service实现
* @createDate 2025-08-04 17:55:06
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginRequest userLoginRequest) {
        Assert.notNull(userLoginRequest, "登录请求体不能为空");
        Assert.hasText(userLoginRequest.getUsername(), "用户名不能为空");
        Assert.hasText(userLoginRequest.getPassword(), "密码不能为空");
        User user = this.lambdaQuery().eq(User::getUsername, userLoginRequest.getUsername()).one();
        Assert.notNull(user, "用户不存在");
        // 密码加密
        String reqPassword = SaSecureUtil.sha256(userLoginRequest.getPassword());
        Assert.isTrue(user.getPassword().equals(reqPassword), "用户名或密码错误！");
        // 登录
        StpUtil.login(user.getId());
        // 脱敏
        UserVO userVO = BeanUtil.toBean(user, UserVO.class);
        // 存储当前用户
        StpUtil.getSession().set("user", user);
        // 返回结果
        UserLoginVO result = new UserLoginVO();
        result.setUser(userVO);
        result.setToken(StpUtil.getTokenValue());
        result.setExpireTime(StpUtil.getTokenTimeout());
        return result;
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @Override
    public Long register(UserRegisterRequest userRegisterRequest) {
        Assert.notNull(userRegisterRequest, "注册请求体不能为空");
        Assert.hasText(userRegisterRequest.getUsername(), "用户名不能为空");
        Assert.hasText(userRegisterRequest.getPassword(), "密码不能为空");
        Assert.hasText(userRegisterRequest.getEmail(), "邮箱不能为空");
        Assert.hasText(userRegisterRequest.getCode(), "验证码不能为空");
        Assert.hasText(userRegisterRequest.getConfirmPassword(), "确认密码不能为空");
        Assert.state(userRegisterRequest.getPassword().equals(userRegisterRequest.getConfirmPassword()), "密码不一致！");
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.CODE_PREFIX + userRegisterRequest.getEmail());
        Assert.notNull(code, "验证码错误");
        // 匹配验证码 忽略大小写
        Assert.state(code.equalsIgnoreCase(userRegisterRequest.getCode()), "验证码错误");
        // 邮箱唯一性校验
        Assert.state(this.lambdaQuery().eq(User::getEmail, userRegisterRequest.getEmail()).count() == 0, "邮箱已存在");
        // 密码加密
        String password = SaSecureUtil.sha256(userRegisterRequest.getPassword());
        User user = new User();
        user.setUsername(userRegisterRequest.getUsername());
        user.setPassword( password);
        user.setEmail(userRegisterRequest.getEmail());
        user.setStatus(0);

        // 保存用户
        boolean save = this.save(user);
        Assert.state(save, "注册失败");

        return user.getId();
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    @Override
    public UserVO getCurrentUser() {
        User user = StpUtil.getSession().getModel("user", User.class);
        return BeanUtil.toBean(user, UserVO.class);
    }

    /**
     * 获取验证码
     *
     * @param email
     * @return
     */
    @Override
    public Boolean getCode(String email) {
        Assert.hasText(email, "邮箱不能为空");
        String code = RandomUtil.randomString(4);
        stringRedisTemplate.opsForValue().set(RedisConstant.CODE_PREFIX + email, code
                , 5 * 60, TimeUnit.SECONDS);
        log.info("邮箱：{}，验证码：{}", email, code);

        // 开启一个线程发送邮件
        Thread.startVirtualThread(()->{
            try {
                String Content = """
                        你的验证码为：%s,有效期为5分钟，如非本人操作，请忽略本邮件。
                        """;
//                emailSendUtil.sendEmail(email,"AI智能体平台",String.format(Content,code));
                EmailMqDTO mqDTO = EmailMqDTO.builder()
                        .title("灵犀灵溪医疗助手平台")
                        .Content(String.format(Content, code))
                        .email(email).build();
                rabbitTemplate.convertAndSend("X","X-Q_EMAIL", JSON.toJSONString(mqDTO));
            } catch (Exception e) {
                log.error("发送验证码失败", e);
            }
        });
        return true;
    }

    /**
     * 修改用户
     *
     * @param userUpdateRequest
     * @return
     */
    @Override
    public Boolean usersUpdate(UserUpdateRequest userUpdateRequest) {
        Assert.notNull(userUpdateRequest, "请求不能为空");
        Assert.notNull(userUpdateRequest.getCode(), "验证码不能为空");
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.CODE_PREFIX + userUpdateRequest.getEmail());
        Assert.notNull(code, "验证码错误");
        // 匹配验证码 忽略大小写
        Assert.state(code.equalsIgnoreCase(userUpdateRequest.getCode()), "验证码错误");
        // 将验证码过期
        stringRedisTemplate.delete(RedisConstant.CODE_PREFIX + userUpdateRequest.getEmail());
        if (Strings.isNotBlank(userUpdateRequest.getPassword())) {
            // 密码加密
            String password = SaSecureUtil.sha256(userUpdateRequest.getPassword());
            userUpdateRequest.setPassword(password);
        }
        User user = StpUtil.getSession().getModel("user", User.class);
        BeanUtil.copyProperties(userUpdateRequest, user);

        boolean result = this.updateById(user);
        if (result) {
            User one = super.lambdaQuery().eq(User::getId, user.getId()).one();
            StpUtil.getSession().set("user",one);
        }
        return result;
    }
}




